package com.ebelter.btcomlib.models.excel;


import com.ebelter.btcomlib.common.IOrder;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.FileUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import jxl.Workbook;

import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * Created by pan on 2018/7/5
 */

public class ExcelUtils extends BaseHandle{

    private static final String TAG = "ExcelUtils";




    private static WritableFont arial14font = null;
    private static WritableCellFormat arial14format = null;
    private static WritableFont arial10font = null;
    private static WritableCellFormat arial10format = null;
    private static WritableFont arial12font = null;
    private static WritableCellFormat arial12format = null;
    private boolean farmatIsSuccess;//格式化字体是否成功的标志


    //是否正在写数据的标志
    private boolean isWriteDateingFlag;

    //public  int index = 1;// 写入序号
    public int row = 2;// 具体字段写入从第二行开始

    public boolean creatExcel(File file, String[] colName){

        if (file==null||colName==null||colName.length==0){
            return false;
        }

        if (!file.getParentFile().exists()){
            FileUtils.makeDir(file.getParentFile());//创建文件夹
        }

        if (file.exists()){
            file.delete();
        }

        format();

        isWriteDateingFlag = true;

       // this.index=0;// 写入序号
        this.row=2;// 具体字段写入从第二行开始

        WritableWorkbook workbook = null;

        boolean result;

        try {
            file.createNewFile();
            workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("Sheet 1", 0);// 建立sheet
            sheet.mergeCells(0, 0, colName.length - 1, 0);
            sheet.addCell((WritableCell) new Label(0, 0, file.getName(), arial14format));// 表头设置完成
            int row = 1;

            for (int col = 0; col < colName.length; col++) {
                sheet.addCell(new Label(col, row, colName[col], arial10format));// 写入// col名称
            }
            workbook.write();// 写入数据
            result=true;
        }catch (Exception e){
            e.printStackTrace();
            result=false;
        }finally {
            try {
                workbook.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }






        return result;
    }

    //初始化格式
    private void format() {
        if (farmatIsSuccess){return;}//如果字体已经格式化成功了就没必要重复格式化了
        try {
            //14号字体
            arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);//设置字体 大小 粗细
            arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);//设置颜色

            arial14format = new WritableCellFormat(arial14font);
            arial14format.setAlignment(jxl.format.Alignment.CENTRE);//设置中间对齐
            arial14format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);//设置边框
            arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);//设置背景颜色

            //10号字体
            arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
            arial10format = new WritableCellFormat(arial10font);
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
            arial10format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            arial10format.setBackground(jxl.format.Colour.LIGHT_BLUE);

            //12号字体
            arial12font = new WritableFont(WritableFont.ARIAL, 12);
            arial12format = new WritableCellFormat(arial12font);
            arial12format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
            farmatIsSuccess=true;
        } catch (WriteException e) {
            farmatIsSuccess=false;
            e.printStackTrace();
        }
    }



//    mExcelUtils.creatExcel(new File(FileUtils.getSDPath()+"/1Test2/text.xls"),col);
//                mExcelUtils.writeObjListToExcel(datas,FileUtils.getSDPath()+"/1Test2/text.xls",col,this);


    public <T> void outExcelData(File file, List<T> objList, String[] fieldArr, final IOrder order){
        boolean su = creatExcel(file,fieldArr);

        if (!su){

            isWriteDateingFlag = false;
            post(new Runnable() {
                @Override
                public void run() {
                    order.cmd(0,0);
                }
            });
            return;
        }

        writeObjListToExcel(objList,file.getAbsolutePath(),fieldArr,order);

    }



    private   <T> void writeObjListToExcel(List<T> objList, String fileName, String[] fieldArr,final IOrder order) {
        if (objList != null && objList.size() > 0) {
            WritableWorkbook writebook = null;
            InputStream in = null;
            try {
                /**
                 * 读取原来写入的文件
                 */
                // WorkbookSettings setEncode = new WorkbookSettings();
                // //设置读文件编码
                // setEncode.setEncoding(UTF8_ENCODING);
                in = new FileInputStream(new File(fileName));
                Workbook workbook = Workbook.getWorkbook(in);
                writebook = Workbook.createWorkbook(new File(fileName), workbook);
                WritableSheet sheet = writebook.getSheet(0);
                /**
                 * 写入数据
                 */
                // {"序号","体验卡号","手机号码","用户iTV帐号","地区","使用时间","体验到期时间","体验期是否订购"};

                for (Object tmp : objList) {
                   // Class classType = tmp.getClass();
                    int col = 0;
                 //   index++;
                 //   String serialNumberStr = String.valueOf(index);
                  //  sheet.addCell(new Label(col, row, serialNumberStr, arial12format));// 第一列用来写序号

                   // LogUtils.i(TAG,"A--col="+col+"---row="+row+"---");

                    /**
                     * 通过反射取值，并且写入到excel中
                     */
                    for (String fieldName : fieldArr) {

                        Object value = getValueByRef(tmp, fieldName);
                        String str;
                        if (value == null) {
                            str = "";
                        } else {
                            str = String.valueOf(value);
                        }
                        sheet.addCell(new Label(col, row, str, arial12format));
                        LogUtils.i(TAG, "----------B--col=" + col + "---row=" + row + "---" + str);
                        col++;
                    }
                    row++;
                }
                writebook.write();

               // Toast.makeText(c, "成功导出 123", Toast.LENGTH_LONG).show();

                post(new Runnable() {
                    @Override
                    public void run() {
                        order.cmd(1,1);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                post(new Runnable() {
                    @Override
                    public void run() {
                        order.cmd(0,0);
                    }
                });
            } finally {

                if (writebook != null) {
                    try {
                        writebook.close();
                    } catch (WriteException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }if(in != null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                isWriteDateingFlag = false;
            }

        }
    }

    public  Object getValueByRef(Object srcObj, String fieldName){
        Object value = null;
        Class objClass = srcObj.getClass();
        fieldName =fieldName.replaceFirst(fieldName.substring(0, 1), fieldName.substring(0, 1).toUpperCase());
        String getMethodName = "get"+fieldName;
        try {
            Method method = objClass.getMethod(getMethodName);//第一个参数为调用的方法名。第二个为方法的返回值:类型
            value = method.invoke(srcObj);///第一个参数表示要调用的对象，后者为传给这个方法的参数
        }  catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return value;
    }


}
